package com.sangfor.ssl.l3vpn.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.VpnService;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.util.Pair;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.common.Foreground;
import com.sangfor.ssl.service.utils.IOUtils;
import java.net.Socket;
import java.util.List;
import okhttp3.internal.http2.Http2Stream;
import okhttp3.internal.ws.RealWebSocket;

/* loaded from: classes2.dex */
public class EasyappSvpnService extends VpnService {
    private static final int EASYAPP_SVPN_SERVICE_ID = 10;
    private static final String EASYAPP_SVPN__CHANNEL_ID = "vpn_tunnel_notification_channelid";
    private static final String LAUNCH_TYPE_KEY = "vpnservice.launch.nettype";
    private static final String LOGIN_STATE_KEY = "vpnservice.launch.loginstate";
    private static final String TAG = "EasyappSvpnService";
    private IManager mTunManager;
    private VpnServiceManager mVpnManager;

    /* loaded from: classes2.dex */
    public interface ICallback {
        void onServiceRevoke(IManager iManager);

        void onServiceStart(IManager iManager, LaunchMode launchMode, LoginState loginState);

        void onServiceStop();
    }

    /* loaded from: classes2.dex */
    public interface IManager {
        void closeTunnel();

        ParcelFileDescriptor openTunnel(TunConfig tunConfig);

        boolean protect(int i);

        boolean protect(Socket socket);

        void stopVpnService();
    }

    @Override // android.app.Service
    public void onCreate() {
        Notification.Builder builder;
        super.onCreate();
        NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
        if (Build.VERSION.SDK_INT >= 26 && notificationManager.getNotificationChannel(EASYAPP_SVPN__CHANNEL_ID) == null) {
            Log.info(TAG, "onCreate create channel:vpn_tunnel_notification_channelid");
            NotificationChannel notificationChannel = new NotificationChannel(EASYAPP_SVPN__CHANNEL_ID, "Tunnel vpn notification", 4);
            notificationChannel.enableLights(true);
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        if (Build.VERSION.SDK_INT >= 26) {
            builder = new Notification.Builder(this, EASYAPP_SVPN__CHANNEL_ID);
        } else {
            builder = new Notification.Builder(this);
        }
        Log.info(TAG, "onCreate startForeground");
        startForeground(10, builder.build());
        Log.info(TAG, "VpnService onCreate.");
    }

    @Override // android.app.Service
    public int onStartCommand(Intent intent, int i, int i2) {
        super.onStartCommand(intent, i, i2);
        Log.info(TAG, "VpnService onStartCommand, EasyappSvpnService start." + Log.getTimestamp());
        if (intent == null || !intent.hasExtra("vpnservice.launch.nettype") || !intent.hasExtra("vpnservice.launch.loginstate")) {
            Log.info(TAG, "VpnService onStartCommand, EasyappSvpnService start. intent is null");
            if (this.mVpnManager == null || this.mTunManager == null) {
                Log.error(TAG, "EasyAppVpnService is pulled up error! VpnManager or TunnelManager is null!");
                stopSelf();
                return 2;
            }
            return 2;
        }
        this.mVpnManager = VpnServiceManager.getInstance();
        if (this.mTunManager == null) {
            this.mTunManager = new TunnelManager(this);
        }
        if (this.mVpnManager.isInit().booleanValue()) {
            this.mVpnManager.onServiceStart(this.mTunManager, getLaunchMode(intent), getLoginState(intent));
            return 2;
        }
        return 2;
    }

    @Override // android.net.VpnService
    public void onRevoke() {
        super.onRevoke();
        Log.info(TAG, "VpnService onRevoke, EasyappSvpnService permission already revoke.");
        this.mVpnManager.onServiceRevoke(this.mTunManager);
    }

    @Override // android.app.Service
    public void onDestroy() {
        super.onDestroy();
        Log.info(TAG, "VpnService onDestroy, EasyappSvpnService stop.");
        this.mVpnManager.onServiceStop();
        this.mTunManager = null;
        if (Build.VERSION.SDK_INT >= 26) {
            stopForeground(true);
        } else {
            stopSelf();
        }
    }

    private LaunchMode getLaunchMode(Intent intent) {
        return LaunchMode.valueOf(intent.getIntExtra("vpnservice.launch.nettype", -1));
    }

    private LoginState getLoginState(Intent intent) {
        return LoginState.valueOf(intent.getIntExtra("vpnservice.launch.loginstate", -1));
    }

    /* loaded from: classes2.dex */
    public static final class TunnelManager implements IManager {
        private VpnService mService;
        int retryEstablishTunnel = 0;
        private ParcelFileDescriptor mDescriptor = null;

        public TunnelManager(VpnService vpnService) {
            this.mService = vpnService;
        }

        @Override // com.sangfor.ssl.l3vpn.service.EasyappSvpnService.IManager
        public ParcelFileDescriptor openTunnel(TunConfig tunConfig) {
            Log.info(EasyappSvpnService.TAG, "openTunnel begin..." + Log.getTimestamp());
            if (tunConfig == null || !tunConfig.isValid()) {
                throw new IllegalArgumentException(" config is " + tunConfig);
            }
            closeTunnel();
            this.retryEstablishTunnel = 0;
            compatOpenTunnel(tunConfig);
            if (this.mDescriptor == null) {
                VpnServiceManager.getInstance().dispatchVpnStatusChangedEvent(VpnStatus.VPN_STATUS_DISCONNECTED.intValue(), 32);
            }
            Log.info(EasyappSvpnService.TAG, "openTunnel end..." + Log.getTimestamp());
            return this.mDescriptor;
        }

        private void compatOpenTunnel(TunConfig tunConfig) {
            try {
                Thread.sleep(Foreground.CHECK_DELAY);
            } catch (InterruptedException e) {
                Log.error(EasyappSvpnService.TAG, "closeTunnel and openTunnel", e);
            }
            try {
                VpnService vpnService = this.mService;
                vpnService.getClass();
                VpnService.Builder builder = new VpnService.Builder(vpnService);
                setupConfig(builder, tunConfig);
                this.mDescriptor = builder.establish();
                Log.debug(EasyappSvpnService.TAG, "openTunnel , config is " + tunConfig.toString());
            } catch (Exception e2) {
                Log.error(EasyappSvpnService.TAG, "openTunnel failed, config is " + tunConfig.toString(), e2);
                int i = this.retryEstablishTunnel;
                if (i < 5) {
                    this.retryEstablishTunnel = i + 1;
                    compatOpenTunnel(tunConfig);
                }
            }
        }

        @Override // com.sangfor.ssl.l3vpn.service.EasyappSvpnService.IManager
        public void stopVpnService() {
            VpnService vpnService = this.mService;
            if (vpnService != null) {
                vpnService.stopSelf();
            }
        }

        @Override // com.sangfor.ssl.l3vpn.service.EasyappSvpnService.IManager
        public boolean protect(int i) {
            return this.mService.protect(i);
        }

        @Override // com.sangfor.ssl.l3vpn.service.EasyappSvpnService.IManager
        public boolean protect(Socket socket) {
            return this.mService.protect(socket);
        }

        @Override // com.sangfor.ssl.l3vpn.service.EasyappSvpnService.IManager
        public void closeTunnel() {
            IOUtils.closeQuietly(this.mDescriptor);
            ParcelFileDescriptor parcelFileDescriptor = this.mDescriptor;
            if (parcelFileDescriptor != null) {
                try {
                    parcelFileDescriptor.detachFd();
                } catch (IllegalStateException e) {
                    Log.info(EasyappSvpnService.TAG, "closeTunnel:" + e.getMessage());
                }
            }
            this.mDescriptor = null;
            Log.info(EasyappSvpnService.TAG, "opt_l3vpn_close_tunnel");
        }

        private void setupConfig(VpnService.Builder builder, TunConfig tunConfig) {
            builder.addAddress(tunConfig.virIp, 32);
            builder.setMtu(tunConfig.mtu);
            builder.setSession(tunConfig.description);
            addRoutes(builder, tunConfig);
            addAllowedApplications(builder, tunConfig);
        }

        private void addRoutes(VpnService.Builder builder, TunConfig tunConfig) {
            try {
                RouteUtil routeUtil = new RouteUtil(builder);
                List<String> list = tunConfig.dnsServer;
                int i = 0;
                if (list != null) {
                    int size = list.size();
                    for (int i2 = 0; i2 < size; i2++) {
                        if (!TextUtils.equals(list.get(i2), "0.0.0.0")) {
                            routeUtil.addDnsRoute(list.get(i2));
                            routeUtil.addRoute(list.get(i2));
                        }
                    }
                }
                List<Pair<String, String>> list2 = tunConfig.routes;
                while (list2 != null) {
                    if (i >= list2.size()) {
                        return;
                    }
                    Pair<String, String> pair = list2.get(i);
                    routeUtil.addRoute((String) pair.first, (String) pair.second);
                    i++;
                }
            } catch (IllegalArgumentException e) {
                Log.error(EasyappSvpnService.TAG, "setupConfig failed, invalid host.");
                e.printStackTrace();
            }
        }

        private void addAllowedApplications(VpnService.Builder builder, TunConfig tunConfig) {
            if (Build.VERSION.SDK_INT < 21) {
                Log.error(EasyappSvpnService.TAG, "addallowedApplication is not support,for android version is lowwer than 5.0 ");
                return;
            }
            try {
                List<String> list = tunConfig.whiteList;
                if (list != null && list.size() != 0) {
                    int size = list.size();
                    for (int i = 0; i < size; i++) {
                        String str = list.get(i);
                        builder.addAllowedApplication(str);
                        Log.info(EasyappSvpnService.TAG, "add whitelistApp: " + str);
                    }
                    return;
                }
                Log.error(EasyappSvpnService.TAG, "whitelistApps is empty!");
            } catch (PackageManager.NameNotFoundException e) {
                Log.error(EasyappSvpnService.TAG, "addAllowedApplications failed, invalid host.");
                e.printStackTrace();
            }
        }

        private void addDisAllowedApplications(VpnService.Builder builder, TunConfig tunConfig) {
            if (Build.VERSION.SDK_INT < 21) {
                Log.error(EasyappSvpnService.TAG, "adddisallowedApplication is not support,for android version is lowwer than 5.0 ");
                return;
            }
            try {
                List<String> list = tunConfig.blackList;
                if (list == null) {
                    Log.error(EasyappSvpnService.TAG, "blackListApps is null!!");
                    return;
                }
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    String str = list.get(i);
                    builder.addDisallowedApplication(str);
                    Log.info(EasyappSvpnService.TAG, " add blacklistApp: " + str);
                }
            } catch (PackageManager.NameNotFoundException e) {
                Log.error(EasyappSvpnService.TAG, "addDisAllowedApplications failed, invalid host.");
                e.printStackTrace();
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public static class RouteUtil {
        private static final int INVALID_HOST = -100;
        private static final long[] SUBNETMASK = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE, 2048, 4096, 8192, Http2Stream.EMIT_BUFFER_SIZE, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456};
        private static final int[] SUBNETMASK_LEN = {32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4};
        private static final String TAG = "RouteUtil";
        private VpnService.Builder mBuilder;

        public RouteUtil(VpnService.Builder builder) {
            this.mBuilder = builder;
        }

        public void addRoute(String str) throws IllegalArgumentException {
            addRoute(str, str);
        }

        public void addDnsRoute(String str) {
            try {
                this.mBuilder.addDnsServer(str);
            } catch (Exception unused) {
                Log.error(TAG, "add Dns Server failed, address is " + str);
            }
        }

        public void addRoute(String str, String str2) throws IllegalArgumentException {
            long ipToLong = IPRcManager.ipToLong(str);
            long ipToLong2 = IPRcManager.ipToLong(str2);
            if (ipToLong == -100 || ipToLong2 == -100 || ipToLong > ipToLong2) {
                throw new IllegalArgumentException("Invalid host, start = " + ipToLong + ",end = " + ipToLong2);
            }
            addRoute(ipToLong, ipToLong2, this.mBuilder);
        }

        private void addRoute(long j, long j2, VpnService.Builder builder) {
            long j3 = j2 == -1 ? j2 - 1 : j2;
            long j4 = (j3 - j) + 1;
            long j5 = j;
            while (j5 <= j3) {
                if (j5 % 2 == 1) {
                    String makeIpStr = IPRcManager.makeIpStr(j5);
                    try {
                        Log.debug(TAG, "add route,host: " + makeIpStr + ", subnetmask: 32");
                        builder.addRoute(makeIpStr, 32);
                    } catch (IllegalArgumentException unused) {
                        Log.error(TAG, "add route failed, invalid argument, host = " + makeIpStr);
                    }
                    j5++;
                    j4--;
                } else {
                    int length = SUBNETMASK.length - 1;
                    while (true) {
                        if (length >= 0) {
                            long[] jArr = SUBNETMASK;
                            if (j5 % jArr[length] == 0 && jArr[length] <= j4) {
                                String makeIpStr2 = IPRcManager.makeIpStr(j5);
                                try {
                                    StringBuilder sb = new StringBuilder();
                                    sb.append("add route,host: ");
                                    sb.append(makeIpStr2);
                                    sb.append(", subnetmask: ");
                                    int[] iArr = SUBNETMASK_LEN;
                                    sb.append(iArr[length]);
                                    Log.debug(TAG, sb.toString());
                                    builder.addRoute(makeIpStr2, iArr[length]);
                                } catch (IllegalArgumentException unused2) {
                                    Log.error(TAG, "add route failed, invalid host = " + makeIpStr2 + ",submasklen = " + SUBNETMASK_LEN[length]);
                                }
                                long[] jArr2 = SUBNETMASK;
                                j5 += jArr2[length];
                                j4 -= jArr2[length];
                                break;
                            }
                            length--;
                        }
                    }
                }
            }
        }
    }
}
